package cn.xyafu.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.xyafu.po.News;
import cn.xyafu.po.Page;
import cn.xyafu.po.User;
import cn.xyafu.service.NewsService;
import cn.xyafu.service.UserService;

@Controller
@Transactional
public class NewsController {
    @Autowired
    private NewsService newsService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询显示消息
     */
    @RequestMapping("/showNews")
    public String showNews(HttpSession session, HttpServletRequest req, Model model){
        User user = (User) session.getAttribute("USER_SESSION");
        //分页显示评论
        Page page = (Page) session.getAttribute("news_page");
        //删除操作后，更新page
        String del = req.getParameter("del");
        System.out.println("del:"+del);
        if (del != null && del != ""){
            page = new Page(1, 5);
            page.setTotal(this.newsService.countNewsByUser(user));
        }
        //判断是否为首次点开
        if (page == null) {      //首次点开
            page = new Page(1, 5);
            page.setTotal(this.newsService.countNewsByUser(user));
        } else {
            String str = req.getParameter("set");       //获取翻页操作
            int nowPage = page.getStart();              //当前页码
            if ("add".equals(str)) {                 //下一页
                if (page.isHasNext()) {          //已是尾页

                } else {
                    page.setStart(nowPage + 1);
                }
            } else if ("sub".equals(str)) {           //上一页
                if (!page.isHasPreviouse()) {             //已是首页

                } else {
                    page.setStart(nowPage - 1);
                }
            } else if ("top".equals(str)) {           //首页
                page.setStart(1);
            } else if ("bottom".equals(str)) {        //尾页
                page.setStart(page.getTotalPage());
            }
        }
        List<News> newsList = null;
        Integer start = (page.getStart() - 1) * page.getCount();
        Integer end = page.getCount();

        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("start",start);
        map.put("end",end);
        map.put("user",user);

        newsList = this.newsService.findNewsByUser(map);

        session.setAttribute("newsList",newsList);
        session.setAttribute("news_page", page);

        return "redirect:my.jsp?my_action=news";
    }

    /**
     * 跳转至message发送消息界面
     */
    @RequestMapping("/toSendNews")
    public String toSendNews(HttpServletRequest request,String rid,String lid){
        //rid 获取接收者信息（ nikename）
        User user = new User();
        user.setUid(Integer.parseInt(rid));
        user.setUnikename(this.userService.findUserByUid(Integer.parseInt(rid)).getUnikename());
        request.setAttribute("lid",lid);
        request.setAttribute("receive",user);
        return "message";
    }

    /**
     * 发送消息
     */
    @RequestMapping("/sendNews")
    public void sendNews(String rid, String nmsg, String lid, HttpServletResponse response, HttpSession session){
        News news = new News();
        User receive = new User();
        receive.setUid(Integer.parseInt(rid));
        news.setSend((User) session.getAttribute("USER_SESSION"));
        news.setReceive(receive);
        news.setNmsg(nmsg);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        news.setNdate(sdf.format(new Date()));
        this.newsService.addNews(news);
        try {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.getWriter().print("<script>alert('消息已发送！');window.location.href='/Lost_ssm/showLost?lostId="+lid+"&cpage=cpage'</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除收到的消息
     */
    @RequestMapping("/deleteNews")
    public String delereNews(String nid,HttpSession session){
        News news = new News();
        news.setReceive((User) session.getAttribute("USER_SESSION"));
        news.setNid(Integer.parseInt(nid));
        this.newsService.deleteNewsByNews(news);
        return "forward:showNews";
    }

}
